package main

import (
	"crypto/tls"
	"crypto/x509"
	"gitee.com/ling-bin/network/Receivers"
	"gitee.com/ling-bin/network/netClient"
	"gitee.com/ling-bin/network/netInterface"
	"io/ioutil"
	"log"
	"time"
)

var (
	mapClient = make(map[int]netClient.IClient, 10000)
)

func main() {
	count := 10000
	for i := 0; i < count; i++ {
		Connects(i)
	}
	for {
		time1 := time.Now()
		for _, client := range mapClient {
			client.SendData([]byte("(client)"), "")
		}
		log.Println(time.Now().Sub(time1).Seconds())
		time.Sleep(time.Second)
	}
}

func Connects(index int) {
	certFile := "D:\\Project\\GoProject\\network\\apps\\client.pem"
	keyFile := "D:\\Project\\GoProject\\network\\apps\\client.pem"
	crt, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return
	}
	certBytes, err := ioutil.ReadFile(certFile)
	if err != nil {
		return
	}
	clientCertPool := x509.NewCertPool()
	ok := clientCertPool.AppendCertsFromPEM(certBytes)
	if !ok {
		return
	}
	tlsConfig := &tls.Config{}
	tlsConfig.Certificates = []tls.Certificate{crt}
	/*验证客户端*/
	tlsConfig.RootCAs = clientCertPool
	tlsConfig.InsecureSkipVerify = true

	config := netClient.NewConfig("tcp", "192.168.1.24:7018",tlsConfig, true)
	client := netClient.NewClient(config)
	client.SetOnReceive(ReceiveTls1)
	client.SetOnConnStart(func(connection netInterface.IConnection) {
		//log.Println("连接成功！")
	})
	client.SetOnConnStop(func(connection netInterface.IConnection) {
		log.Println("连接断开！")
	})
	//加入分包逻辑
	client.SetHandleStrategy(func(connection netInterface.IConnection, bytes []byte) *netInterface.StrategyData {
		receiver := make([]netInterface.IReceiver, 0, 2)
		receiver = append(receiver, Receivers.NewSpliceSymbolReceiver(0x28, 0x29))
		return &netInterface.StrategyData{
			Key: "",
			Receivers: receiver,
		}
	})
	//设置日志处理
	client.SetLogHandle(func(level netInterface.ErrLevel, msg string) {
		switch level {
		case netInterface.Fatal:
			log.Println("[致命]", msg)
			break
		case netInterface.Error:
			log.Println("[致命]", msg)
			break
		case netInterface.Warn:
			log.Println("[警告]", msg)
			break
		case netInterface.Info:
			log.Println("[消息]", msg)
			break
		}
	})
	_, err = client.Connect()
	if err == nil {
		mapClient[index] = client
	}
}

// ReceiveTls1 数据接收
func ReceiveTls1(connection netInterface.IConnection, data []byte) {
	//fmt.Println("接收数据:", string(data))
	//fmt.Println("启动时间：", connection.GetStartTime().Format("2006-01-02 15:04:05"))
	//fmt.Println("心跳时间：", connection.GetHeartTime().Format("2006-01-02 15:04:05"))
	//fmt.Println("接收信息：")
	//fmt.Println(connection.GetRecInfo())
	//fmt.Println("发送信息：")
	//fmt.Println(connection.GetRepInfo())
}
